# from collections import OrderedDict
# from django.conf import settings
# from django.template import loader
# import os
# import time
#
# from goods.models import GoodsChannel
# from contents.models import ContentCategory
#
#
# def generate_static_index_html():
#     """
#     生成静态的主页html文件
#     """
#     print('%s: generate_static_index_html' % time.ctime())
#     # 商品频道及分类菜单
#     # 使用有序字典保存类别的顺序
#     # categories = {
#     #     1: { # 组1
#     #         'channels': [{'id':, 'name':, 'url':},{}, {}...],
#     #        一级下 二级分类'sub_cats': [{'id':, 'name':, 三级分类'sub_cats':[{},{}]}, {}, {}, ..]
#     #     },
#     #     2: { # 组2
#     #
#     #     }
#     # }
#
#     # 从数据库中查询出首页所需的商品分类和首页广告数据
#     categories = OrderedDict()
#     # 获取商品频道信息
#     channels = GoodsChannel.objects.order_by('group_id', 'sequence')
#     for channel in channels:
#         group_id = channel.group_id  # 当前组
#
#         if group_id not in categories:
#             categories[group_id] = {'channels': [], 'sub_cats': []}
#
#         # 获取频道对应的一级分类
#         cat1 = channel.category  # 当前频道的类别
#
#         # 追加当前频道
#         categories[group_id]['channels'].append({
#             'id': cat1.id,
#             'name': cat1.name,
#             'url': channel.url
#         })
#         # 构建当前类别的子类别  一级分类下的二级分类（省市县一样）
#         for cat2 in cat1.goodscategory_set.all():
#             # 向二级分类下加三级分类
#
#             cat2.sub_cats = []
#             for cat3 in cat2.goodscategory_set.all():
#                 cat2.sub_cats.append(cat3)
#
#             categories[group_id]['sub_cats'].append(cat2)
#
#     # 获取首页广告数据
#     contents = {}
#     # 广告内容类别
#     content_categories = ContentCategory.objects.all()
#     for cat in content_categories:
#         # key广告的类别识别键名：当前类别下的广告  一对多取法 cat.content_set
#         contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
#
#     # 渲染模板
#     context = {
#         'categories': categories,
#         'contents': contents
#     }
#     # 加载模版：指定使用的模版文件，获取模版对象
#     template = loader.get_template('index.html')
#     # 模版渲染
#     html_text = template.render(context)
#     file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')
#
#     # 保存  将渲染后的html文件页面内容保存生成一个静态页面
#     with open(file_path, 'w', encoding='utf-8') as f:
#         f.write(html_text)
import os
import time
from collections import OrderedDict
from django.conf import settings

from contents.models import ContentCategory
from goods.models import GoodsChannel


def generate_static_index_html():
    """生成首页的静态页面index.html"""
    print('generate_static_index_html: %s' % time.ctime())
    # 1. 从数据库中查询出首页所需的`商品分类`和`首页广告`数据
    # categories = {
    #     '<group_id>': [
    #         'channels': [{'id': '一级分类id', 'name': '一级分类名称', 'url': '频道页面地址'}, ...],
    #         'sub_cats': [{'id': '二级分类id',
    #                       'name': '二级分类名称',
    #                       'sub_cats': [{'id': '三级分类id', 'name': '三级分类名称'}, ...]},
    #                     ...]
    #     ],
    #     ...
    # }

    # 保存商品的分类数据
    categories = OrderedDict()

    # 获取商品频道信息
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    for channel in channels:
        group_id = channel.group_id

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        # 获取频道对应一级分类
        cat1 = channel.category

        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })

        for cat2 in cat1.goodscategory_set.all():
            cat2.sub_cats = []

            for cat3 in cat2.goodscategory_set.all():
                cat2.sub_cats.append(cat3)

            categories[group_id]['sub_cats'].append(cat2)

    # 获取首页的广告数据
    # {
    #     '类别识别键名': '当前类别下的广告',
    #     ...
    # }
    contents = {}
    content_categories = ContentCategory.objects.all()

    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    # 2. 调用模板`index.html`，给模板文件传数据，进行模板渲染，获取渲染之后的html页面内容
    context = {
        'categories': categories,
        'contents': contents
    }

    # 1）加载模板：指定所使用的模板文件，获取模板对象
    from django.template import loader
    temp = loader.get_template('index.html')

    # 2）模板渲染：给模板文件传数据，将模板文件中的变量进行替换，获取渲染之后的html页面内容
    res_html = temp.render(context)

    # 3. 将渲染之后的html页面内容保存成一个静态页面
    save_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')

    with open(save_path, 'w', encoding='utf8') as f:
        f.write(res_html)

